package dp;

/**
 * leet-code(213) 打家劫舍
 *
 * @author Ringo
 * @date 2021/8/21 20:52
 */
public class Rob2 {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 1};
        System.out.println(rob(nums));
    }

    public static int rob(int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        if (nums.length == 1)
            return nums[0];
        if (nums.length == 2)
            return Math.max(nums[0], nums[1]);
        int n = nums.length;
        return Math.max(robRange(nums, 1, n - 1), robRange(nums, 0, n - 2));
    }

    public static int robRange(int[] nums, int start, int end) {
        int n = end - start + 1;
        if (n == 1) return nums[start];
        if (n == 2) return Math.max(nums[start], nums[start + 1]);
        int[] dp = new int[n];
        dp[0] = nums[start];
        dp[1] = Math.max(nums[start], nums[start + 1]);
        int ans = 0;
        for (int i = 2; i < n; i++) {
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[start + i]);
            ans = Math.max(ans, dp[i]);
        }
        return ans;
    }
}
